package com.zenitera.bigdata.tableapiflinksql;

import com.zenitera.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * Table API - Group Windows - 会话窗口
 * Session
 */
public class Flink04_TableApi_GroupWindow03 {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorDataStreamSource = env.fromElements(
                new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60))

                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
                );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table table = tableEnv.fromDataStream(waterSensorDataStreamSource, $("id"), $("ts").rowtime(), $("vc"));

        table
                .window(Session.withGap(lit(6).second()).on($("ts")).as("timestamp"))
                .groupBy($("id"), $("timestamp"))
                .select($("id"), $("timestamp").start().as("start_time"), $("timestamp").end().as("end_time"), $("vc").sum().as("vc_sum"))
                .execute()
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
/*
+----+--------------------------------+-------------------------+-------------------------+-------------+
| op |                             id |              start_time |                end_time |      vc_sum |
+----+--------------------------------+-------------------------+-------------------------+-------------+
| +I |                       sensor_1 | 1970-01-01 00:00:01.000 | 1970-01-01 00:00:11.000 |         120 |
| +I |                       sensor_2 | 1970-01-01 00:00:03.000 | 1970-01-01 00:00:12.000 |          90 |
+----+--------------------------------+-------------------------+-------------------------+-------------+
 */